/*
 * Copyright 2004-2011 Paolo Conte
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jellylab.ojoverse.net.html;

import java.lang.reflect.Field;
import java.sql.Types;
import org.jellylab.ojoverse.Column;
import org.jellylab.ojoverse.DataObject;
import org.jellylab.ojoverse.DataWrapper;

public class FormGenerator {

    public FormGenerator(DataWrapper wrapper, DataObject data) throws IllegalArgumentException, IllegalAccessException {
        Field[] fields = data.getDataFields();

        if (fields == null) {
            throw new IllegalArgumentException("Fields array cannot be null.");
        }

        int fieldLen = fields.length;

        StringBuffer htmlcode = new StringBuffer(1000);
        for (int idf = 0; idf < fieldLen; idf++) {
            Field field = fields[idf];
            String fieldName = field.getName();
            Column column = (Column)wrapper.getColumns().get(fieldName);

            int fieldType = column.getDatatype().getType();

            Object fieldValue = field.get(data);

            if (DataWrapper.isType(fieldType, Types.VARCHAR)) {
                htmlcode.append("type=\"text\"");
            }

            // consider only fields not null
            if (fieldValue != null) {
                if (htmlcode.length() > 0) {
                    htmlcode.append(" AND ");
                }
                htmlcode.append(column.getDBName());
                htmlcode.append('?');
            }
        }
    }
}
